package com.ad.pet.app.mall;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ad.pet.App;
import com.ad.pet.DaggerMainActivityCompent;
import com.ad.pet.R;
import com.ad.pet.app.Navigation;
import com.ad.pet.app.RxDisposable;
import com.ad.pet.app.account.adapter.AccountPetAdapter;
import com.ad.pet.app.mall.adapter.DateWeekAdapter;
import com.ad.pet.app.mall.adapter.DayTimeAdapter;
import com.ad.pet.app.mall.adapter.TipsDoorAdapter;
import com.ad.pet.common.data.http.BusCall;
import com.ad.pet.common.data.utils.date.DateUtil;
import com.ad.pet.common.data.utils.ui.ToastUtil;
import com.ad.pet.common.structure.events.RxBus;
import com.ad.pet.common.structure.mvp.BasePresenter;
import com.ad.pet.common.structure.ui.activity.AppToolbarActivity;
import com.ad.pet.models.remote.account.AccountPet;
import com.ad.pet.models.remote.mall.ChoseOrder;
import com.ad.pet.models.remote.mall.Counpous;
import com.ad.pet.models.remote.mall.OrderDate;
import com.ad.pet.models.remote.mall.OrderDoorInfo;
import com.ad.pet.models.remote.mall.ServiceDetail;
import com.ad.pet.models.remote.mall.SkuPirce;
import com.ad.pet.models.remote.mall.WeekDoor;
import com.ad.pet.ui.MaxRecyclerView;
import com.ad.pet.ui.SimpleDividerDecoration;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.just.agentweb.LogUtils;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import rx.android.schedulers.AndroidSchedulers;

/**
 * Created by liuyixiang on 2019/11/18.
 */

public class DoorOrderActivity extends AppToolbarActivity implements ServiceDetailContracts.View {
    @BindView(R.id.tv_contact)
    EditText tvContact;
    @BindView(R.id.tv_phone)
    EditText tvPhone;

    @BindView(R.id.tv_yuyue_store)
    TextView tvYuyueStore;

    @BindView(R.id.tv_project)
    TextView tvProject;

    @BindView(R.id.recycler_pet)
    MaxRecyclerView recyclerPet;

    @BindView(R.id.recycler_project)
    MaxRecyclerView recyclerProject;
    @BindView(R.id.recycler_data)
    MaxRecyclerView recyclerData;
    @BindView(R.id.recycler_time)
    MaxRecyclerView recyclerTime;
    @BindView(R.id.recycler_other)
    MaxRecyclerView recyclerOther;
    @BindView(R.id.tv_pet_name)
    TextView tvPetName;
    @BindView(R.id.tv_chose_time)
    TextView tvChoseTime;

    @BindView(R.id.btn_commit)
    Button btnCommit;

    @BindView(R.id.tv_counpous)
    TextView tvCounpous;

    @Inject
    RxDisposable mRxDisposable;

    @Inject
    ServiceDetailPresenter serviceDetailPresenter;
    @BindView(R.id.relativce_youhuiquan)
    RelativeLayout relativceYouhuiquan;
    private AccountPetAdapter accountPetAdapter;
    private String date;
    private String shopId;
    private ChoseOrder choseOrder;
    private String petId;
    private List<OrderDate> orderDates;
    private DayTimeAdapter dayTimeAdapter;
    private DateWeekAdapter dateWeekAdapter;
    private List<WeekDoor> weekDoors;
    private WeekDoor weekDoor;
    private OrderDate selectOrderDate;
    private Counpous counpous;

    @Override
    protected void init(Bundle savedInstanceState) {
        super.init(savedInstanceState);
        mStatusLayoutManager.showContent();
        mToolbar.setBackgroundColor(getResources().getColor(R.color.colorAccent));
        mToolbar.setTitle("门店预约");

        mToolbar.getTitleView().setTextColor(getResources().getColor(R.color.white));
        mToolbar.setLeftIcon(R.drawable.whitefanhui);

//        R.layout.item_pet_service_project_layout
//        R.layout.item_week_layout
//        R.layout.item_service_time_layout
//        R.layout.item_service_pet_info
    }

    @Override
    protected int contentLayout() {
        return R.layout.activity_door_order_activity;
    }

    @Override
    protected void clickRetry(View v) {

    }

    @Override
    protected void onResume() {
        super.onResume();


    }

    @Override
    protected void initViews() {
        serviceDetailPresenter.onCreate(this);
        choseOrder = (ChoseOrder) getIntent().getSerializableExtra("order");
        shopId = choseOrder.getShop_id();
        tvContact.setText(App.username);
        tvPhone.setText(App.phone);
        StringBuffer skuName = new StringBuffer();
        skuName.append(choseOrder.getOffservice_name());
        skuName.append(" ");
        String nskName = choseOrder.getOffservice_sku_name().replaceAll(",", " ");

        skuName.append(nskName);
        LogUtils.e("sku--->", skuName.toString());
        tvProject.setText(skuName.toString());
        tvYuyueStore.setText(choseOrder.getShop_name());

        accountPetAdapter = new AccountPetAdapter(null);
        recyclerPet.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        recyclerPet.setAdapter(accountPetAdapter);

        recyclerTime.setLayoutManager(new GridLayoutManager(this, 6));
        dayTimeAdapter = new DayTimeAdapter(null);
        recyclerTime.addItemDecoration(new SimpleDividerDecoration(mActivity, 24, R.color.transparent));
        recyclerTime.setAdapter(dayTimeAdapter);


        List<String> xuzhiList = new ArrayList<>();

        xuzhiList.add("情绪不稳定，带有攻击性的犬只");
        xuzhiList.add("小于4个月且免疫未全的幼犬，大于6岁的老龄犬");
        xuzhiList.add("有心脏病、肺炎、癫痫等先天病史的犬只");
        xuzhiList.add("有犬瘟、细小、冠状流感等传染性疾病犬只");
        xuzhiList.add("最近一周内进行过免疫、外科手术的犬只");
        xuzhiList.add("已经怀孕的犬只");

        recyclerOther.setLayoutManager(new LinearLayoutManager(this));
        TipsDoorAdapter tipsDoorAdapter = new TipsDoorAdapter(xuzhiList);
        recyclerOther.setAdapter(tipsDoorAdapter);


    }

    @Override
    protected void initData() {
        long time = System.currentTimeMillis();
        date = DateUtil.stampToDate(time);

        long time1 = time + 86400000;
        long time2 = time + 86400000 * 2;
        long time3 = time + 86400000 * 3;
        long time4 = time + 86400000 * 4;
        long time5 = time + 86400000 * 5;
        long time6 = time + 86400000 * 6;


        weekDoors = new ArrayList<>();
        weekDoors.add(new WeekDoor(DateUtil.getWeekOfDate(time), DateUtil.stampToDate(time, "MM/dd"), time, true));
        weekDoors.add(new WeekDoor(DateUtil.getWeekOfDate(time1), DateUtil.stampToDate(time1, "MM/dd"), time1, false));
        weekDoors.add(new WeekDoor(DateUtil.getWeekOfDate(time2), DateUtil.stampToDate(time2, "MM/dd"), time2, false));
        weekDoors.add(new WeekDoor(DateUtil.getWeekOfDate(time3), DateUtil.stampToDate(time3, "MM/dd"), time3, false));
        weekDoors.add(new WeekDoor(DateUtil.getWeekOfDate(time4), DateUtil.stampToDate(time4, "MM/dd"), time4, false));
        weekDoors.add(new WeekDoor(DateUtil.getWeekOfDate(time5), DateUtil.stampToDate(time5, "MM/dd"), time5, false));
        weekDoors.add(new WeekDoor(DateUtil.getWeekOfDate(time6), DateUtil.stampToDate(time6, "MM/dd"), time6, false));

        weekDoor = weekDoors.get(0);
        recyclerData.setLayoutManager(new GridLayoutManager(this, 7));
        dateWeekAdapter = new DateWeekAdapter(weekDoors);
        recyclerData.setAdapter(dateWeekAdapter);

        serviceDetailPresenter.getDoorBasicInfo(date, shopId);
    }

    @Override
    protected void initEvents() {

        mRxDisposable.add(RxBus.getDefault().toObservable(String.class)
                .observeOn(AndroidSchedulers.mainThread()).subscribe(new BusCall<String>() {
                    @Override
                    public void call(String webTitle) {
                        if ("up_pet_head_success".equals(webTitle)) {
                                serviceDetailPresenter.getDoorBasicInfo(date,shopId);
                        }
                    }
                }));
        accountPetAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                AccountPet accountPet = accountPetAdapter.getItem(position);
                if ("-1".equals(accountPet.getPet_id())) {
                    Navigation.goPetInfo(mActivity, accountPetAdapter.getItem(position).getPet_id());
                    return;
                }
                petId = accountPet.getPet_id();
                tvPetName.setText(accountPet.getPet_name());
                for (int i = 0; i < accountPetAdapter.getData().size(); i++) {
                    accountPetAdapter.getData().get(i).setChose(i==position);
                }
                accountPetAdapter.notifyDataSetChanged();
            }
        });

        dayTimeAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                OrderDate orderDate = dayTimeAdapter.getItem(position);
                long curTime = System.currentTimeMillis()+30*1000*60;
                long itemTime = DateUtil.dateToStamp(orderDate.getYear() + " " + orderDate.getDate() + ":00");
                if (curTime > itemTime || orderDate.getDate_count() == 1) {
                    return;
                }
                for (int i = 0; i < dayTimeAdapter.getData().size(); i++) {
                    if (i == position) {
                        dayTimeAdapter.getData().get(i).setChose(true);
                        selectOrderDate = dayTimeAdapter.getItem(i);
                    } else {
                        dayTimeAdapter.getData().get(i).setChose(false);
                    }
                }
                if (weekDoor != null && selectOrderDate != null) {
                    tvChoseTime.setText(DateUtil.stampToDate(weekDoor.getTime()) + " | " + selectOrderDate.getDate());
                }
                dayTimeAdapter.notifyDataSetChanged();
            }
        });
        dateWeekAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                weekDoor = dateWeekAdapter.getItem(position);
                for (int i = 0; i < dateWeekAdapter.getData().size(); i++) {
                    if (i == position) {
                        dateWeekAdapter.getData().get(i).setChose(true);
                    } else {
                        dateWeekAdapter.getData().get(i).setChose(false);
                    }

                }

                dateWeekAdapter.notifyDataSetChanged();
                serviceDetailPresenter.getDoorBasicInfo(DateUtil.stampToDate(weekDoor.getTime()), shopId);
            }
        });
        relativceYouhuiquan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
              String p =  dateWeekAdapter.getWeekDoor().getWeekday();

                Navigation.goChoseCounpus(mActivity,choseOrder.getOffservice_id(),DateUtil.getWeekPosition(p) );
            }
        });
        btnCommit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(tvContact.getText().toString())){
                    ToastUtil.getToastUtil().showShort("请输入联系人");
                    return;
                }
                if (TextUtils.isEmpty(tvPhone.getText().toString())){
                    ToastUtil.getToastUtil().showShort("请输入联系电话");
                    return;
                }
                if (TextUtils.isEmpty(petId)){
                    ToastUtil.getToastUtil().showShort("请选择爱宠");
                    return;
                }
                if (TextUtils.isEmpty(tvChoseTime.getText().toString())){
                    ToastUtil.getToastUtil().showShort("请选择服务时间");
                    return;
                }
                String[] chosetime=tvChoseTime.getText().toString().split("\\|");
                serviceDetailPresenter.upDoorOrder(tvContact.getText().toString(),tvPhone.getText().toString(),shopId,petId,choseOrder.getOffservice_id(),choseOrder.getOffservice_name(),choseOrder.getOffservice_sku_id(),choseOrder.getOffservice_sku_name(),chosetime[0].trim(),chosetime[1].trim()+":00",counpous==null?"":counpous.getVoucher_id(),choseOrder.getPrice());
            }
        });
    }

    @Override
    public void initInject() {
        DaggerMainActivityCompent.builder().applicationComponent(getApplicationComponent()).activityModule(getActivityModule()).build().inject(this);
    }

    @Override
    protected BasePresenter getPresenter() {
        return null;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void error(String msg) {

    }

    @Override
    public void error(int code, String msg) {

    }

    @Override
    public void getServiceDetialSuccess(ServiceDetail serviceDetail) {

    }

    @Override
    public void getSkuPriceDetailSuccess(SkuPirce skuPirce) {

    }

    @Override
    public void getDoorBasicInfoSuccess(OrderDoorInfo orderDoorInfo) {
        List<AccountPet> list = orderDoorInfo.getPet_list();
        list.add(new AccountPet("-1", ""));
        accountPetAdapter.setNewData(list);
        orderDates = orderDoorInfo.getDate_list();

        for (int i = 0; i < orderDates.size(); i++) {
            orderDates.get(i).setYear(DateUtil.stampToDate(weekDoor.getTime()));
        }
        dayTimeAdapter.setNewData(orderDates);

    }

    @Override
    public void upDoorOrderSuccess() {
        RxBus.getDefault().post("close_door");
        ToastUtil.getToastUtil().showShort("预约成功");
        finish();
    }

    @Override
    public void addServiceSuccess() {

    }

    @Override
    public void cancelServiceSuccess() {

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data == null)
            return;
        if (requestCode == 211 && resultCode == RESULT_OK) {
            counpous = (Counpous) data.getSerializableExtra("youhuiquan");
            tvCounpous.setText(counpous.getVoucher_name());
        }
    }
}
